/*
 * Created on Jan 1, 2005
 */
package org.scohen.juploadr.prefs;

import java.io.File;
import java.util.Locale;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

import org.scohen.juploadr.uploadapi.Account;

/**
 * @author steve
 */
public class Configuration {
    private static final String MAC_OS = "Mac OS X"; //$NON-NLS-1$
    public static final int DEFAULT_PROXY_PORT = 8080;
    private String PASSWORD_KEY = "password";
    private String EMAIL_KEY = "email";
    private String SHOULD_ENCRYPT_PASSWORD_KEY = "shouldEncryptPassword";
    private String ACCOUNT_TYPE_KEY = "accountType";
    private String MONTHLY_ALLOWABLE_UPLOAD_KEY = "monthlyAllowableUpload";
    private String CURRENT_UPLOAD_KEY = "currentUpload";
    private String DEFAULT_PRIVACY_SETTING_KEY = "defaultPrivacy";
    private String PROXY_ENABLED_KEY = "proxyEnabled";
    private String PROXY_HOST_KEY = "proxyHost";
    private String PROXY_PORT_KEY = "proxyPort";
    private String PROXY_USERNAME_KEY = "proxyUsername";
    private String PROXY_PASSWORD_KEY = "proxyPassword";
    private String USE_IMAGE_LAYOVERS_KEY = "useImageLayovers";
    private String AUTHED_TOKEN_KEY = "authedTokenKey";
    private String LAST_AUTHED_DATE_KEY = "lastAuthedDate";
    private String DEFAULT_TAGS_KEY = "defaultTags";
    private String AUTO_REMOVE_UPLOADED_PHOTOS_KEY = "autoRemoveUploadedPhotos";
    private String AUTO_RESIZE_PHOTOS_KEY = "autoResizePhotos";
    private String MAX_PHOTO_SIZE_KEY = "maxPhotoSize";
    private String AUTH_TOKEN_KEY = "authToken";
    private String UPLOAD_BY_EXIF_DATE_KEY = "uploadByExifDate";
    private String VERSION_UPGRADE_ACK_KEY = "lastVersionAcked";
    private String LANGUAGE_KEY = "language";
    private String THROTTLING_ENABLED = "useThrottling";
    private String THROTTLING_MAX_KBPS = "throttlingKBPS";
    private String UPLOAD_API_CLASS_KEY = "uploadApi";
    private String SCALING_QUALITY_KEY = "favorScalingQuality";

    private Locale[] locales = { Locale.ENGLISH, Locale.FRENCH, new Locale("es"), Locale.ITALIAN,Locale.GERMAN, new Locale("pt"),
            new Locale("pl") };
    private Preferences prefs;

    private static Configuration instance;
    private String version;

    static {
        instance = new Configuration();
    }

    /**
     * @return Returns the instance.
     */
    public static Configuration getInstance() {

        return instance;
    }

    protected Configuration() {
        prefs = Preferences.userNodeForPackage(Configuration.class);

    }

    public void upgradeComplete() {
        prefs.remove(PASSWORD_KEY);
        prefs.remove(EMAIL_KEY);
        prefs.remove(SHOULD_ENCRYPT_PASSWORD_KEY);
        prefs.remove(ACCOUNT_TYPE_KEY);
        prefs.remove(MONTHLY_ALLOWABLE_UPLOAD_KEY);
        prefs.remove(CURRENT_UPLOAD_KEY);
        prefs.remove(LAST_AUTHED_DATE_KEY);
        prefs.remove(AUTH_TOKEN_KEY);
        prefs.remove(AUTHED_TOKEN_KEY);
        prefs.remove(DEFAULT_PRIVACY_SETTING_KEY);
        prefs.remove(DEFAULT_TAGS_KEY);
    }

    public boolean hasUpgraded() {
        return prefs.getInt(DEFAULT_PRIVACY_SETTING_KEY, -1024) < 0;
    }

    public int getDefaultPrivacySetting() {
        return prefs.getInt(DEFAULT_PRIVACY_SETTING_KEY, Account.PRIVACY_PUBLIC);
    }

    public String getDefaultTags() {
        return prefs.get(DEFAULT_TAGS_KEY, "");
    }

    public boolean isProxyEnabled() {
        return prefs.getBoolean(PROXY_ENABLED_KEY, false);
    }

    public String getOldUsername() {
        return prefs.get(EMAIL_KEY, "");
    }

    public String getOldToken() {
        return prefs.get(AUTH_TOKEN_KEY, "");
    }

    /**
     * @param b
     */
    public void setProxyEnabled(boolean enabled) {
        prefs.putBoolean(PROXY_ENABLED_KEY, enabled);

    }

    public void setProxyHost(String hostname) {
        prefs.put(PROXY_HOST_KEY, hostname);
    }

    public String getProxyHost() {
        return prefs.get(PROXY_HOST_KEY, "");
    }

    public void setProxyPort(int port) {
        prefs.putInt(PROXY_PORT_KEY, port);
    }

    public int getProxyPort() {
        return prefs.getInt(PROXY_PORT_KEY, DEFAULT_PROXY_PORT);
    }

    public void setProxyUsername(String name) {
        prefs.put(PROXY_USERNAME_KEY, name);
    }

    public String getProxyUsername() {
        return prefs.get(PROXY_USERNAME_KEY, "");
    }

    public void setProxyPassword(String pass) {
        prefs.put(PROXY_PASSWORD_KEY, pass);
    }

    public String getProxyPassword() {
        return prefs.get(PROXY_PASSWORD_KEY, "");
    }

    public boolean proxySettingsValid() {
        return getProxyHost().length() > 0;
    }

    public void setUseImageLayovers(boolean useIt) {
        prefs.putBoolean(USE_IMAGE_LAYOVERS_KEY, useIt);
    }

    public boolean getUseImageLayovers() {
        return prefs.getBoolean(USE_IMAGE_LAYOVERS_KEY, true);
    }

    public boolean getAutoRemoveUploadedPhotos() {
        return prefs.getBoolean(AUTO_REMOVE_UPLOADED_PHOTOS_KEY, false);
    }

    public void setAutoRemoveUploadedPhotos(boolean remove) {
        prefs.putBoolean(AUTO_REMOVE_UPLOADED_PHOTOS_KEY, remove);
    }

    public void setAutoResizePhotos(boolean resize) {
        prefs.putBoolean(AUTO_RESIZE_PHOTOS_KEY, resize);
    }

    public boolean getAutoResizePhotos() {
        return prefs.getBoolean(AUTO_RESIZE_PHOTOS_KEY, false);
    }

    public void setMaxPhotoSize(int size) {
        prefs.putInt(MAX_PHOTO_SIZE_KEY, size);
    }

    public int getMaxPhotoSize() {
        return prefs.getInt(MAX_PHOTO_SIZE_KEY, 0);
    }

    public Locale getLocale() {
        Locale rv = Locale.getDefault();
        String lang = prefs.get(LANGUAGE_KEY, null);

        if (lang != null) {
            rv = new Locale(lang);
        }
        return rv;
    }

    public Locale[] getValidLocales() {
        return locales;
    }

    public void setLocale(Locale locale) {
        prefs.put(LANGUAGE_KEY, locale.getLanguage());
    }

    public boolean getUploadByExifDate() {
        return prefs.getBoolean(UPLOAD_BY_EXIF_DATE_KEY, false);
    }

    public void setUploadByExifDate(boolean shouldUpload) {
        prefs.putBoolean(UPLOAD_BY_EXIF_DATE_KEY, shouldUpload);
    }

    public String getVersion() {
        if (version == null) {
            try {
                File f;
                if (isMac()) {
                    f = new File(System.getProperty("user.dir"),
                            "JUploadr.app/Contents/Resources/Java/juploadr.jar");
                } else {
                    f = new File(System.getProperty("user.dir"), "lib" + File.separator + "juploadr.jar");
                }
                JarFile jar = new JarFile(f);
                Manifest mf = jar.getManifest();
                Map entries = mf.getMainAttributes();
                version = (String) entries.get(new Attributes.Name("Version"));
            } catch (Exception e) {
               System.out.println(e.getMessage() + " when getting version (shouldn't happen except in dev)" );
            }
        }
        if (version == null) {
            version = "Development";
        }
        return version;
    }

    public boolean shouldUpgradeTo(String version) {
        if (version.equals(getVersion()) || version.equals(getLastVersionAcked())
                || getVersion().equals("Development")) {
            return false;
        }
        Version local = new Version(getVersion());
        Version remote = new Version(version);
        return local.compareTo(remote) < 0;
    }

    public void setLastVersionAcked(String ver) {
        prefs.put(VERSION_UPGRADE_ACK_KEY, ver);
    }

    public String getLastVersionAcked() {
        return prefs.get(VERSION_UPGRADE_ACK_KEY, "");
    }

    public void resetAllPrefs() {
        try {
            prefs.clear();
        } catch (BackingStoreException e) {
            e.printStackTrace();
        }
    }

    public boolean isThrottlingEnabled() {
        return prefs.getBoolean(THROTTLING_ENABLED, false);
    }

    public void setThrottlingEnabled(boolean isEnabled) {
        prefs.putBoolean(THROTTLING_ENABLED, isEnabled);
    }

    public void setMaxKPerSecond(int kPerSecond) {
        prefs.putInt(THROTTLING_MAX_KBPS, kPerSecond);
    }

    public int getMaxKPerSecond() {
        return prefs.getInt(THROTTLING_MAX_KBPS, Integer.MAX_VALUE);
    }

    public String getUploadApiClassName() {
        return prefs.get(UPLOAD_API_CLASS_KEY, "org.scohen.juploadr.uploadapi.flickrrest.RestFlickrApi");
    }

    public void setUploadApiClassName(String name) {
        prefs.put(UPLOAD_API_CLASS_KEY, name);
    }

    public static boolean isMac() {
        return MAC_OS.equals(System.getProperty("os.name"));
    }

    public void setImageIORescalerEnabled(boolean b) {
        prefs.putBoolean(SCALING_QUALITY_KEY, b);
    }

    public boolean isScalingQualityFavored() {
        return prefs.getBoolean(SCALING_QUALITY_KEY, false);
    }

}